package com.tss.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tss.pojo.Result;
import com.tss.pojo.User;
import com.tss.service.UserService;
import com.tss.utils.CodeUtil;

@Controller
@RequestMapping("user")
public class UserController {
	@Autowired
	private UserService userService;
//	
//	@Autowired
//	private HttpRequest request;
	
	/**
	 * 注册新用户
	 * @param user
	 * @return
	 */
	@RequestMapping("register")
	@ResponseBody
	public String register(User user){
		Result result = new Result();
		if(user==null||user.getNickname()==null||user.getPassword()==null){
			result.setErrorMessage("参数不能为空。");
			return result.toString();
		}
		if(userService.addUser(user)){
			result.setSuccessMessage("注册成功！");
			return result.toString();
		}
		result.setErrorMessage("注册失败！");
		return result.toString();
	}
	
	@RequestMapping("login")
	@ResponseBody
	public String login(HttpServletRequest request,HttpServletResponse response,User user){
		Result result = new Result();
		if(user==null){
			result.setErrorMessage("参数不能为空。");
			return result.toString();
		}
		User u = userService.findUser(user);
		if(u!=null){
			if(u.getPassword().equals(user.getPassword())){
				String uuid = CodeUtil.getUUID();
				Cookie cookie = new Cookie("token",uuid);
				cookie.setMaxAge(60*60);
				response.addCookie(cookie);
				request.getSession().setMaxInactiveInterval(60*60);
				request.getSession().setAttribute("token", uuid);
				request.getSession().setAttribute("nickname", u.getNickname());
				result.setSuccessMessage("登录成功！");
				return result.toString();
			}else{
				return result.setErrorMessage("用户密码错误！").toString();
			}
		}
		result.setErrorMessage("登录失败！");
		return result.toString();
	}
	
	@RequestMapping("check")
	@ResponseBody
	public String check(String nickname){
		Result result = new Result();
		User user = new User();
		user.setNickname(nickname);
		user = userService.findUser(user);
		if(user==null){
			result.setMessage("账号不存在！");
			result.setStatus(Result.STATUS_CODE_INEXISTENT);
			return result.toString();
		}else{
			result.setMessage("账号存在！");
			result.setStatus(Result.STATUS_CODE_EXISTENT);
			return result.toString();
		}
		
	}
	
	
}
